import sqlite3
import copy
import os
from SqliteHandler import SqliteHandler
from SqlDict import SqlDict


class Table5rate:

    # key值 应该为 函数字符串 可以eval
    rate_example = {
        '勘察费': '0',
        '设计费': '0',
        '安全生产费': '0',
        '建设工程监理费': '0',
        '审计费': '0',
    }

    def __init__(self, prototype='book1', *args, **kwargs):

        # prototype 参数 book1 电源设备 book2 有线设备 book3 无线设备 book4 线路工程 book5 管道工程
        # kwargs中 equ 为需要安装设备费 （元）
        # con 为建筑安装工程费 （元）
        # dis 为勘察长度 （km） pip为管道 bury为直埋 common为管道架空 underw为水底 unders为海底 rate为折扣等（类型为字符串‘0.8*0.9）
        # safebase 为国标建筑安装工程费(除税价)

        self.rate = copy.deepcopy(self.rate_example)
        self.path = kwargs.get('path')
        self.equ = kwargs.get('equ', 0)
        self.con = kwargs.get('con', 0)
        self.safebase = kwargs.get('safebase', 0)
        self.dis = kwargs.get('dis', 0)
        # 五种长度
        self.dis_pip = kwargs.get('dis_pip', 0)
        self.dis_bury = kwargs.get('dis_bury', 0)
        self.dis_common = kwargs.get('dis_common', 0)
        self.dis_underw = kwargs.get('dis_underw', 0)
        self.dis_unders = kwargs.get('dis_unders', 0)
        # 阶段设计系数
        self.stage_rate = kwargs.get('stage_rate', '1')
        # 五种长度分别的rate
        self.dis_pip_rate = kwargs.get('dis_pip_rate')
        self.dis_bury_rate = kwargs.get('dis_bury_rate')
        self.dis_common_rate = kwargs.get('dis_common_rate')
        self.dis_underw_rate = kwargs.get('dis_underw_rate')
        self.dis_unders_rate = kwargs.get('dis_unders_rate')
        # 设计费 监理费 安全生产费 审计费 rate
        self.design_rate = kwargs.get('design_rate')
        self.supervision_rate = kwargs.get('supervision_rate')
        self.safe_rate = kwargs.get('safe_rate')
        self.audit_rate = kwargs.get('audit_rate')
        # 自定义 勘察费 设计费 监理费 安全生产费 审计费
        self.survey_custom = kwargs.get('survey_custom')
        self.design_custom = kwargs.get('design_custom')
        self.supervision_custom = kwargs.get('supervision_custom')
        self.safe_custom = kwargs.get('safe_custom')
        self.audit_custom = kwargs.get('audit_custom')

        self.strconandequ = self.conandequ()

        self.conn = SqliteHandler(self.path)

        if self.design_rate == '1':
            self.design_rate = None
        if self.supervision_rate == '1':
            self.supervision_rate = None
        if self.safe_rate == '1':
            self.safe_rate = None
        if self.audit_rate == '1':
            self.audit_rate = None
        if self.dis_pip_rate == '1':
            self.dis_pip_rate = None
        if self.dis_bury_rate == '1':
            self.dis_bury_rate = None
        if self.dis_common_rate == '1':
            self.dis_common_rate = None
        if self.dis_underw_rate == '1':
            self.dis_underw_rate = None
        if self.dis_unders_rate == '1':
            self.dis_unders_rate = None

        self.get_survey(prototype)
        self.get_supervision()
        self.get_safe(prototype)
        self.get_audit(prototype)

        self.conn.close()

    def getrate(self):
        return self.rate

    def conandequ(self):
        if self.equ == 0 and self.con == 0:
            return '0'
        elif self.equ == 0 and self.con != 0:
            return str(self.con)
        elif self.equ != 0 and self.con == 0:
            return str(self.equ)
        else:
            return str(self.equ) + '+' + str(self.con)

    def get_survey(self, prototype):
        # 勘察费
        if self.dis_bury == 0 and self.dis_common == 0 and self.dis_pip == 0 and self.dis_underw == 0 and self.dis_unders == 0:
            return
        dbdict = {
            'Survey_cable': [self.dis_bury, self.dis_bury_rate],
            'Survey_fiber': [self.dis_common, self.dis_common_rate],
            'Survey_pip': [self.dis_pip, self.dis_pip_rate],
            'Survey_undersea': [self.dis_underw, self.dis_underw_rate],
            'Survey_underwater': [self.dis_unders, self.dis_unders_rate],
        }
        totalres = ''
        res = ''
        for name in dbdict:
            res = ''
            data = self.conn.select(name)
            data = self.cursor2list(data)
            for j in data:
                if dbdict[name][0] == 0 and j[1] >= dbdict[name][0]:
                    break
                
                if j[1] < dbdict[name][0]:
                    res = str(j[2]) + '+' + '(' + str(dbdict[name][0]) + \
                        '-' + str(j[1]) + ')' + '*' + str(j[3])

                if res.split('*')[-1] == '0.0':
                    res = res.split('+')[0]

            if dbdict[name][1] is not None and res != '':
                if self.stage_rate is None or float(self.stage_rate) == 1:
                    res = '(' + res + ')*' + dbdict[name][1]
                else:
                    res = '(' + res + ')*' + self.stage_rate + '*' +dbdict[name][1]
            
            if res != '':
                totalres = totalres + '+' + res

        totalres = totalres[1:]
        self.filldictitem(self.rate, '勘察费', totalres)

    def get_supervision(self):
        # 监理费
        dbnames = ['Supervision', 'Design']
        cnames = ['建设工程监理费', '设计费']
        rates = [self.supervision_rate, self.design_rate]
        for index, dbname in enumerate(dbnames):
            data = self.conn.select(dbname)
            data = self.cursor2list(data)
            conandequ = self.con + self.equ
            for j in data:
                if j[1] <= conandequ:
                    res = str(j[2]) + '+' + '(' + self.strconandequ + \
                        '-' + str(j[1]) + ')' + '*' + str(j[3])

            if res.split('+')[0] == '0.0':
                if len(self.strconandequ.split('+')) == 1:
                    res = self.strconandequ + '*' + str(data[0][3])
                else:
                    res = '(' + self.strconandequ + ')' + '*' + str(data[0][3])

            if rates[index] is not None and res != '':
                res = '(' + res + ')*' + str(rates[index])


            # if cnames[index] == '设计费':
            #     res = res + '*1.1'
            self.filldictitem(self.rate, cnames[index], res)

    def get_safe(self, pro):
        # 安全生产费
        dbname = 'safe'
        data = self.conn.select(dbname)
        data = self.cursor2list(data)
        for i in data:
            if i[1] == pro:
                res = str(self.safebase) + '*' + str(i[2]/100)
                if self.safebase < i[3]:
                    res = str(i[3])

        if self.safe_rate is not None and res != '':
            res = '(' + res + ')*' + self.safe_rate

        self.filldictitem(self.rate, '安全生产费', res)

    def get_audit(self, pro):
        # 审计费
        dbname = 'audit'
        data = self.conn.select(dbname)
        data = self.cursor2list(data)
        for i in data:
            if i[1] == pro:
                res = str(self.safebase) + '*' + str(i[2]/100)
                if self.safebase < i[3]:
                    res = str(i[3])

        if self.audit_rate is not None and res != '':
            res = '(' + res + ')*' + self.audit_rate

        self.filldictitem(self.rate, '审计费', res)

    def cursor2list(self, cursor):
        # 将cursor可迭代对象转换为list
        mylist = []
        for i in cursor:
            temp = []
            for j in i:
                temp.append(j)
            mylist.append(temp)

        return mylist

    def filldictitem(self, d, key, item):
        # 将item写入复杂字典对应的key,key不能有重复
        for i in d:
            if not isinstance(d[i], dict):
                if i == key:
                    d[i] = item
                    return
            else:
                self.filldictitem(d[i], key, item)


if __name__ == "__main__":
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    path = os.path.join(BASE_DIR, 'db/Survey.db')
    print(path)
    test = Table5rate('book4', path=path, dis_common=1, dis_pip=1,
                      con=100000000, equ=10000, safebase=20000)
    data = test.getrate()
    print(data)
    for i in data:
        print(eval(data[i]))
